package com.zlsy.secondtime.deadlock;


/**
 * @author zhouliang
 * @date 2020/6/18 10:34
 * <p>
 * 转账的时候遇到死锁，一旦打开注释，便会发生死锁。
 */
public class TransferMoney implements Runnable {

    int flag = 0;
    static Account a = new Account(500);
    static Account b = new Account(500);


    @Override
    public void run() {
        if (flag == 0) {
            transferMoney(a, b, 200);
        }
        if (flag == 1) {
            transferMoney(b, a, 200);
        }
    }

    private void transferMoney(Account from, Account to, int amount) {
        synchronized (from) {
            synchronized (to) {
                if (from.balance - amount < 0) {
                    System.out.println("余额不足！");
                }
                from.balance -= amount;
                to.balance += amount;
                System.out.println("转账完成");
            }
        }
    }

    static class Account {
        private int balance;

        public Account(int balance) {
            this.balance = balance;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TransferMoney r1 = new TransferMoney();
        TransferMoney r2 = new TransferMoney();
        r1.flag = 0;
        r2.flag = 1;

        Thread thread1 = new Thread(r1);
        Thread thread2 = new Thread(r2);
        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("a账户的余额为:" + a.balance);
        System.out.println("b账户的余额为:" + b.balance);
    }
}
